﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Kaskelot.SP.Core;
using Kaskelot.SP.Model.Configuration;

namespace Kaskelot.SP.Services
{
    public class NavigationService
    {
        public NavigationService()
        {
        }

        public IEnumerable<SiteMapNode> GetTopNavigationNodes(SiteMapNode rootNode)
        {
            List<SiteMapNode> nodes = rootNode.ChildNodes.Cast<SiteMapNode>().ToList();
            nodes.Insert(0, rootNode);

            return nodes;
        }

		public IEnumerable<Model.Client.Tab> GetDetailTabs(SPWeb web)
		{
			IEnumerable<Model.Client.Tab> res = null;

			if (web.AllProperties.ContainsKey(Constants.Tabs.TabConfiguration))
			{
				string s = web.AllProperties[Constants.Tabs.TabConfiguration].ToString();
				res = Precio.SharePoint.Core.XmlSerializer<List<Model.Client.Tab>>.DeSerialize(s);
			}
			else
			{
				throw new Exception("TabConfiguration kunde inte hittas");
			}

			return res;
		}

        public IEnumerable<Model.Client.MenuItem> GetToolboxItems(string toolboxConfigId)
        {
            if (toolboxConfigId == null)
                return new List<Model.Client.MenuItem>();

            List<Model.Client.MenuItem> menuItems = new List<Model.Client.MenuItem>();
            string configValue = null;
            try
            {
                configValue = ConfigManager.General.ToolboxConfiguration;

                if (configValue != null)
                {
                    var config = Precio.SharePoint.Core.XmlSerializer<ToolboxConfigurationWrapper>.DeSerialize(configValue).Configurations.Where(c => c.Id.ToLower().StartsWith(toolboxConfigId.ToLower())).FirstOrDefault();
                    if (config != null)
                        menuItems = config.Items;
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(this, LayerNames.Services, "GetToolboxItems", string.Format("NavigationService: Error getting GetToolboxConfiguration for id {0}", toolboxConfigId), ex);                
            }

            return menuItems;
        }
    }
}
